package com.lfk.blog.controller;

import cn.hutool.core.util.StrUtil;
import com.lfk.api.dto.Result;
import com.lfk.blog.utils.JedisPoolUtil;
import com.lfk.blog.utils.QiniuUtils;
import com.lfk.blog.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

import static com.lfk.blog.utils.SystemConstants.pictureHostName;


/**
 * <p>
 *  上传控制层
 * </p>
 *
 * @author Cat凯
 * @since 2023-2-1
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {


    @Autowired
    private QiniuUtils qiniuUtils;
    @PostMapping("blog")
    public Result uploadImage(@RequestParam("file") MultipartFile image) {
//        System.out.println(image.getSize());
        if(image.getSize()>1024*1024*1024){
            throw new RuntimeException("文件过大,上传失败");
        }
        try {
            // 获取原始文件名称
            String originalFilename = image.getOriginalFilename();
            // 生成新文件名
            String fileName = createNewFileName(originalFilename);
            //System.out.println("fileName:"+fileName);
            // 保存文件
//            File temp=new File(new File(SystemConstants.IMAGE_UPLOAD_DIR).getAbsolutePath() + "/" + fileName);
//            image.transferTo(temp);
            fileName=qiniuUtils.upload(image.getBytes(),fileName);
            // 返回结果
            log.debug("文件上传成功，{}", pictureHostName + fileName);
            //使用jedisPool连接池,以set集合形式存放文件名
            JedisPool jedisPool= JedisPoolUtil.getJedisPoolInstance();
            Jedis jedis=jedisPool.getResource();
            jedis.sadd(RedisConstants.SETMEAL_PIC_RESOURCES, fileName);
            jedis.close();
            return Result.ok(fileName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @GetMapping("/blog/delete")
    public Result deleteBlogImg(@RequestParam("name") String filename) {
        /*File file = new File(SystemConstants.IMAGE_UPLOAD_DIR, filename);
        if (file.isDirectory()) {
            return Result.fail("错误的文件名称");
        }
        FileUtil.del(file);*/
        JedisPool jedisPool=JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis=jedisPool.getResource();
        if(!jedis.sismember(RedisConstants.SETMEAL_PIC_RESOURCES,filename)){
            return Result.fail("错误的文件名称");
        }
        jedis.srem(RedisConstants.SETMEAL_PIC_RESOURCES,filename);
        jedis.close();
        return Result.ok();

    }

    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = UUID.randomUUID().toString();
//        int hash = name.hashCode();
//        int d1 = hash & 0xF;
//        int d2 = (hash >> 4) & 0xF;
//        // 判断目录是否存在
//        File dir = new File(new File(SystemConstants.IMAGE_UPLOAD_DIR).getAbsolutePath(), StrUtil.format("/blogs/{}/{}", d1, d2));
//        //System.out.println("dir:"+dir);
//        if (!dir.exists()) {
//            dir.mkdirs();
//        }
        // 生成文件名
        return StrUtil.format("{}.{}", name, suffix);
    }
}
